# Python变量作用域（全局变量和局部变量）
## 局部变量
def demo():
    add = "http://c.biancheng.net/python/"
    print("函数内部 add =", add)

demo()
#print("函数外部 add =", add) # NameError: name 'add' is not defined
print()

def demo(name, add):
    print("函数内部 name =", name)
    print("函数内部 add =", add)

demo("Python教程", "http://c.biancheng.net/python/")
#print("函数外部 name =", name) # NameError: name 'name' is not defined
#print("函数外部 add =", add) # NameError: name 'add' is not defined
print()

## 全局变量
g_add = "http://c.biancheng.net/shell/"
def text():
    print("函数内部访问：", g_add)
text()
print("函数外部访问：", g_add)
print()

# 在函数体内定义全局变量。即使用 global 关键字对变量进行修饰后，该变量就会变为全局变量
def g_text():
    global add_g
    add_g = "http://c.biancheng.net/java/"
    print("函数体内访问：", add_g)
g_text()
print("函数体外访问：", add_g)
print()

## 获取指定作用域范围中的变量
### globals()函数
# 全局变量
Pyname = "Python教程"
Pyadd = "http://c.biancheng.net/python/"
def text():
    # 局部变量
    Shename = "shell教程"
    Sheadd = "http://c.biancheng.net/shell/"

print(globals())
print()

print(globals()["Pyname"])
globals()["Pyname"] = "Python入门教程"
print(Pyname)
print()

### locals()函数
# 全局变量
Pyname = "Python教程"
Pyadd = "http://c.biancheng.net/python/"
def text():
    # 局部变量
    Shename = "shell教程"
    Sheadd = "http://c.biancheng.net/shell/"
    print("函数内部的 locals:")
    print(locals())

text()
print("函数外部的 locals:")
print(locals())
print()

Pyname = "Python教程"
Pyadd = "http://c.biancheng.net/python/"
def text():
    Shename = "shell教程"
    Sheadd = "http://c.biancheng.net/shell/"
    print(locals()['Shename'])
    locals()['Shename'] = "shell入门教程"
    print(Shename)

text()
print()

### vars(object)
# 全局变量
Pyname = "Python教程"
Pyadd = "http://c.biancheng.net/python/"
class Demo:
    name = "Python教程"
    add = "http://c.biancheng.net/python/"
print("有 object:")
print(vars(Demo))
print()

print("无 object:")
print(vars())
